package com.xe.gae.control;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.xe.gae.model.XEConfig;
import com.xe.gae.model.XEResource;

public class XEBlobstoreService {
	
	private BlobstoreService bss = BlobstoreServiceFactory.getBlobstoreService();
    private BlobInfoFactory  bif= new BlobInfoFactory();

    
	public String createUploadUrl(String createUploadUrl) {
		
		String s=bss.createUploadUrl(createUploadUrl);
		
		return s;
		
	}


	public void delete(BlobKey blobKey) {
		bss.delete(blobKey);
	}


	public void serve(BlobKey blobKey, HttpServletResponse res) {
		try {
			bss.serve(blobKey, res);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	public void updateUploadedBlob(HttpServletRequest req) {
		XEDataStorageService dss = new XEDataStorageService();
		Map<String, BlobKey> blobs = bss.getUploadedBlobs(req);
		XEResourcesManager rm = new XEResourcesManager();
		String encodeKeyParent = req.getParameter("resource-key");
		XEResource parent=null;

		if (encodeKeyParent==null){
			parent=rm.getRoot();
		}
		else{
			parent=rm.findByEncodedKey(encodeKeyParent);
		}

		for (String key:blobs.keySet()){
			BlobKey blobKey = blobs.get(key);
			rm.newResource( blobKey, parent);
		
		String extract=req.getParameter("extract");
		if(extract!=null){
			XEConfigManager conf = new XEConfigManager();
			conf.install(blobKey, parent);
			}
		}
		

	}



	
	
	
}
